<?php
class UserController extends Epic_Controller_Action 
{
	public function newAction() {
		Epic::setTitle("Create Account");
		
	}
	public function forgetpassAction (){
	
		// add css
		Epic::addListCssUrl ('account/forgetpass.css');
		//kiem tra mail co hop le ko
		if ($data = $this->getRequest()->getPost()) {
			// Validate
			$errorFlag = false;
			$emailValid = new Epic_Validate_Element_Email($data['email']);	
			if (!$emailValid->isValid()) { // kiem tra xem $data['email'] có đúng định dạng email hay không
				Epic::setError($emailValid->getErrorMessage());
				$errorFlag = true;
				$this->_redirect(Epic::getUrl('account/user/forgetpass'));
			} else {
				Epic::setSuccess("Please check your email!");
				Epic::setFormData($data);
			}
		}
	}
	
	public function saveAction()
	{
		if ($data = $this->getRequest()->getPost()) {
			// Validate
			$errorFlag = false;
			
			if(!$data['username'] || !$data['email'] || !$data['password']) {
				Epic::setError('All field is required.');
				$errorFlag = true;
			} else {
				$emailValid = new Epic_Validate_Element_Email($data['email']);	
	
				if (!$emailValid->isValid()) {
					Epic::setError($emailValid->getErrorMessage());
					$errorFlag = true;
				}
			}
			
			$data['username'] = htmlentities($data['username'], ENT_QUOTES, "UTF-8");
			if($errorFlag) {
				Epic::setFormData($data);
				$this->_redirect(Epic::getUrl('account/user/new'));
			}
			
			// Đảm bảo tài khoản email chưa có ai đăng ký trước đó
			$user = Epic::getModel('account/user');
			$userCheck = $user->load($data['email'], 'email');
	
			if(!is_null($userCheck['email'])) {
				Epic::setFormData($data);
				Epic::setError('Your email address used for registration.');
				$this->_redirect(Epic::getUrl('account/user/new'));
				return;
			}
			
			try {
				// save data
				$data['avatar'] = 'avatar.jpg';
				$user->save($data);
				Epic::setFormData(false); // reset form data
				Epic::setSuccess('The account has been saved.');
			} catch (Exception $e) {
				Epic::setError($e->getMessage());
			}
			$this->_redirect(Epic::getUrl());
		} else {
			Epic::setError('Unable to find article to save');
			$this->_redirect(Epic::getUrl('account/user/new'));
		}
	
	}
	
	public function loginAction()
	{
		header('Cache-control: private');
		$form = new Account_Form_Login();
		
		if ($this->getRequest()->isPost()) {
			if($form->isValid($this->getRequest()->getPost())) {
				$username = $form->getValue('username');
				$password = $form->getValue('password');
				$user = Epic::getModel('account/user')->load($username, 'username');
				if(!is_null($user)) {
					if($user['password'] == $password) {
						$storeUserSession = array(
							'access' => true,
							'avatar' => $user['avatar'],
							'user_id' => $user['user_id'],
							'username' => $user['username'],
							'role' => $user['role'],
							'start' => time());
						Epic::getSession()->set($storeUserSession);
					} else {
						Epic::setError("The Username or Passworld is incorrect");
					}
				} else {
					Epic::setError("The Username or Passworld is incorrect");
				}
			} else {
				Epic::setError($form->getErrorString());
			}
		}
 		$this->_redirect(Epic::getUrl());
	} 
	
	public function logoutAction()
	{
		Epic::getSession()->destroySession();
		$this->_redirect(Epic::getUrl());
	}
	
	public function profileAction() {}
	
	public function editAction() 
	{
		if ($this->getRequest()->isPost()) {
			$userId = Epic::getSession()->get('user_id');
			$path = 'img/base/upload/' . $userId;
			if (!is_dir($path)) {
				mkdir($path);
			}
			
			$uploader = new Epic_File_Upload('avatar');
			$uploader->setAllowedExtensions(array('jpg','jpeg','gif','png'))
					 ->setAllowedMaximum(800);	//800KB
			$result = $uploader->save($path);
			
			// Successful upload
			if($result === true) {
				// Resize image
				$pathFile = $path . '/' . $uploader->getFileName();
				$resize = new Epic_File_Resize($pathFile);
				$resize->resizeImage(60, 60, 'fixedwidth');
				$resize->saveImage($pathFile);
			
				// Create small image
				$newImageName = substr_replace($uploader->getFileName(), '_small', strrpos($uploader->getFileName(), '.'), 0);
				$resize->resizeImage(24, 24, 'fixedwidth');
				$resize->setNewImageName($newImageName);
				$resize->saveImage();
			
				
				Epic::getModel('account/user')->save(
						array('user_id' => $userId, 
						      'avatar' => $userId . '/' . $uploader->getFileName())
				);
			
				// Remove old avatar
				$avatar = Epic::getSession()->get('avatar');
				unlink('img/base/upload/' . $avatar);
				unlink('img/base/upload/' .substr_replace($avatar, '_small', strrpos($avatar, '.'), 0));
				
				Epic::getSession()->set('avatar', $userId . '/' . $uploader->getFileName());
				Epic::setSuccess('The avatar has been upload.');
			} else {
				Epic::setError($result);
			}
			$this->_redirect(Epic::getUrl('account/user/profile'));
		}
	}
}
